package com.anjiplus.template.gaea.auth.modules.websocket;

import com.anji.plus.gaea.constant.GaeaConstant;
import com.anji.plus.gaea.utils.GaeaUtils;
import com.anjiplus.template.gaea.common.config.GaeaRedisListener;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * 监听消息(采用redis发布订阅方式发送消息)
 */
@Slf4j
@Component
public class SocketHandler implements GaeaRedisListener {

    @Autowired
    private WebSocketService webSocket;

    @Override
    public void onMessage(Map<String, String> map) {
        log.info("【SocketHandler消息】Redis Listerer:" + map.toString());
        String username = map.get("username");
        String message = map.get("message");
        String id = map.get("id");
        String nowTime = GaeaUtils.formatDate(new Date(), GaeaConstant.TIME_PATTERN);
        GaeaWsMessage gaeaWsMessage = null;
        if (map.containsKey("eventData")) {
            gaeaWsMessage = new GaeaWsMessage(id, message, nowTime, map.get("eventData"), map.get("eventType"));
        } else {
            gaeaWsMessage = new GaeaWsMessage(id, message, nowTime, map.get("eventType"));
        }
        if (StringUtils.isNotEmpty(username)) {
            webSocket.pushMessage(username, gaeaWsMessage);
        } else {
            webSocket.pushMessage(message, gaeaWsMessage);
        }

    }
}